﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks.Dataflow;

namespace NewSolution
{
    public class SegmentBlock
    {
        private readonly byte[] _pattern;
        private int _LastbufferSize;

        public SegmentBlock(byte[] pattern, int bufferSize)
        {
            _pattern = (byte[])pattern.Clone();
            _LastbufferSize = bufferSize;
        }

        private List<byte> LastBuffer = new List<byte>();
        private int flag = 1;

        public IEnumerable<(byte[], int)> Segmentation(byte[] buffer)
        {
            LastBuffer.AddRange(buffer);

            while (LastBuffer.ToArray().Length > _pattern.Length)
            {
                var temp = LastBuffer.ToArray().AsSpan();
                var result = temp.IndexOf(_pattern);

                if (result != -1)
                {
                    flag = 1;
                    LastBuffer.RemoveRange(0, result + _pattern.Length);
                    yield return (temp[0..result].ToArray(), flag);

                }
                else
                {
                    flag = 0;
                    LastBuffer.RemoveRange(0, (temp.Length - _pattern.Length + 1));
                    yield return (temp[0..(temp.Length - _pattern.Length + 1)].ToArray(), flag);

                }
            }

            if (buffer.Length < _LastbufferSize)
            {
                yield return (LastBuffer.ToArray(), 1);
                LastBuffer.Clear();
            }
        }

        public TransformBlock<byte[], (byte[], int)> CreateTransformBlock()
        {
            return new TransformBlock<byte[], (byte[], int)>(
                buffer =>
                {
                    var segments = Segmentation(buffer).ToList();
                    return segments.First();
                });
        }
    }
}